#include "InteractiveObject.hpp"
#include "KeyboardEvent.hpp"
#include "MouseEvent.hpp"
#include "Utils.hpp"

SDL_Thread *InteractiveObject::thread = NULL;

InteractiveObject::InteractiveObject() : 
    DisplayObject(), running_thread(false)
{
    TRACEIN;
    InteractiveObject::thread = SDL_CreateThread(InteractiveObject::Update, this);

    if (InteractiveObject::thread == NULL ) 
        fprintf(stderr, "Unable to create thread: %s\n", SDL_GetError());
    
    running_thread = true;
    TRACEOUT;
}

InteractiveObject::~InteractiveObject() 
{ TRACEIN; running_thread = false;  SDL_KillThread(thread); TRACEOUT; }

int InteractiveObject::Update(void *data)
{
    TRACEIN;
    InteractiveObject *int_obj = static_cast<InteractiveObject*>(data);
    SDL_Event event;

    while(int_obj->running_thread)
    {
        while(SDL_PollEvent(&event))
        {
            switch(event.type)
            {
                case SDL_KEYUP:
                    int_obj->dispatchEvent(new KeyboardEvent(
                        KeyboardEvent::KEY_UP,
                        event.key.keysym.sym,
                        event.key.keysym.sym));
                    break;
                case SDL_KEYDOWN:
                    int_obj->dispatchEvent(new KeyboardEvent(
                        KeyboardEvent::KEY_DOWN,
                        event.key.keysym.sym,
                        event.key.keysym.sym));
                    break;
            }
        }
    }

    TRACEOUT;
    return 0;
}

